﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.ApplicationServices;
using System.Web.Mvc;
using Classified.Data.Repositories;
using Classified.Service;
using Classified.Web.Services;


namespace Classified.Web
{
    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        public IFormsAuthenticationService AuthenticationService { get; set; }

        public string RequiredRole;

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null) throw new ArgumentNullException("httpContext");
            AuthenticationService =
           new FormsAuthenticationService(new HttpContextWrapper(HttpContext.Current));
            var user = AuthenticationService.GetAuthenticatedUser();
            if (user == null)
                return false;
            
                foreach (var i in user.Roles)
                {
                    if (i.RoleName == RequiredRole)
                    {
                        return true;
                    }
                }
            
            return false;

        }
    }
    //public class AuthWhereRole : AuthorizeAttribute
    //{
    //    /// <summary>
    //    /// Add the allowed roles to this property.
    //    /// </summary>
    //    public Role Is;

    //    /// <summary>
    //    /// Checks to see if the user is authenticated and has the
    //    /// correct role to access a particular view.
    //    /// </summary>
    //    /// <param name="httpContext"></param>
    //    /// <returns></returns>
    //    protected override bool AuthorizeCore(HttpContextBase httpContext)
    //    {
    //        if (httpContext == null)
    //            throw new ArgumentNullException("httpContext");

    //        // Make sure the user is authenticated.
    //        if (!httpContext.User.Identity.IsAuthenticated)
    //            return false;

    //        var authenticationService = new FormsAuthenticationService(new HttpContextWrapper(HttpContext.Current));
    //        var user = authenticationService.GetAuthenticatedUser();
    //        if (user == null)
    //            return false;
    //         // Load the user's role here

    //        // Perform a bitwise operation to see if the user's role
    //        // is in the passed in role values.
    //        if (Is != 0 && ((Is & user.Role.Id) != role))
    //            return false;

    //        return true;
    //    }
    //}
}